// 全局变量
let currentUser = null;
let authToken = null;

// DOM加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 检查是否已登录
    const token = localStorage.getItem('authToken');
    if (token) {
        authToken = token;
        showDashboard();
        loadCurrentUser();
    } else {
        showLoginPage();
    }

    // 绑定事件
    bindEvents();
});

// 绑定事件
function bindEvents() {
    // 登录表单提交
    document.getElementById('login-form').addEventListener('submit', handleLogin);
    
    // 导航菜单点击
    document.querySelectorAll('.nav-link[data-section]').forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            const section = this.getAttribute('data-section');
            showSection(section);
            
            // 更新导航激活状态
            document.querySelectorAll('.nav-link').forEach(navLink => {
                navLink.classList.remove('active');
            });
            this.classList.add('active');
        });
    });
    
    // 退出登录
    document.getElementById('logout-link').addEventListener('click', function(e) {
        e.preventDefault();
        logout();
    });
    
    // 添加用户按钮
    document.getElementById('add-user-btn').addEventListener('click', function() {
        showUserModal();
    });
    
    // 保存用户按钮
    document.getElementById('save-user-btn').addEventListener('click', saveUser);
    
    // 添加云账号按钮
    document.getElementById('add-account-btn').addEventListener('click', function() {
        showAccountModal();
    });
    
    // 保存云账号按钮
    document.getElementById('save-account-btn').addEventListener('click', saveAccount);
}

// 显示登录页面
function showLoginPage() {
    document.getElementById('login-page').classList.remove('d-none');
    document.getElementById('admin-dashboard').classList.add('d-none');
}

// 显示管理台主界面
function showDashboard() {
    document.getElementById('login-page').classList.add('d-none');
    document.getElementById('admin-dashboard').classList.remove('d-none');
    
    // 默认显示仪表盘
    showSection('dashboard');
}

// 显示指定区域
function showSection(sectionName) {
    // 隐藏所有区域
    document.querySelectorAll('.content-section').forEach(section => {
        section.classList.add('d-none');
    });
    
    // 显示指定区域
    document.getElementById(`${sectionName}-section`).classList.remove('d-none');
    
    // 根据区域加载数据
    switch(sectionName) {
        case 'dashboard':
            loadDashboardData();
            break;
        case 'users':
            loadUsers();
            break;
        case 'accounts':
            loadAccounts();
            break;
    }
}

// 处理登录
async function handleLogin(e) {
    e.preventDefault();
    
    const email = document.getElementById('email').value;
    const password = document.getElementById('password').value;
    
    try {
        const response = await fetch('/api/auth/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ email, password })
        });
        
        const data = await response.json();
        
        if (data.success) {
            authToken = data.data.token;
            localStorage.setItem('authToken', authToken);
            
            currentUser = {
                id: data.data.userId,
                username: data.data.username,
                email: data.data.email,
                nickname: data.data.nickname
            };
            
            showDashboard();
            loadCurrentUser();
            showToast('登录成功', 'success');
        } else {
            showToast(data.message || '登录失败', 'danger');
        }
    } catch (error) {
        console.error('登录错误:', error);
        showToast('登录失败，请检查网络连接', 'danger');
    }
}

// 加载当前用户信息
async function loadCurrentUser() {
    try {
        const response = await fetch('/api/auth/current', {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });
        
        const data = await response.json();
        
        if (data.success) {
            currentUser = data.data;
            document.getElementById('current-user-name').textContent = currentUser.nickname || currentUser.email;
        } else {
            logout();
        }
    } catch (error) {
        console.error('获取用户信息错误:', error);
        logout();
    }
}

// 退出登录
function logout() {
    localStorage.removeItem('authToken');
    authToken = null;
    currentUser = null;
    showLoginPage();
    showToast('已退出登录', 'info');
}

// 加载仪表盘数据
async function loadDashboardData() {
    try {
        // 加载用户总数
        const usersResponse = await fetch('/api/users', {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });
        const usersData = await usersResponse.json();
        if (usersData.success) {
            document.getElementById('total-users').textContent = usersData.data.total || 0;
        }
        
        // 加载云账号总数
        const accountsResponse = await fetch('/api/cloud-accounts/current', {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });
        const accountsData = await accountsResponse.json();
        if (accountsData.success) {
            document.getElementById('total-accounts').textContent = accountsData.data.length || 0;
        }
        
        // 存储使用量暂时显示占位符
        document.getElementById('storage-usage').textContent = '-';
    } catch (error) {
        console.error('加载仪表盘数据错误:', error);
    }
}

// 加载用户列表
async function loadUsers() {
    try {
        const response = await fetch('/api/users', {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });
        
        const data = await response.json();
        
        if (data.success) {
            const usersTableBody = document.getElementById('users-table-body');
            usersTableBody.innerHTML = '';
            
            if (data.data.records && data.data.records.length > 0) {
                data.data.records.forEach(user => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${user.id}</td>
                        <td>${user.email}</td>
                        <td>${user.nickname || '-'}</td>
                        <td><span class="badge bg-${user.role === 'ADMIN' ? 'danger' : 'primary'}">${user.role === 'ADMIN' ? '管理员' : '普通用户'}</span></td>
                        <td><span class="badge bg-${user.status === 1 ? 'success' : 'secondary'}">${user.status === 1 ? '启用' : '禁用'}</span></td>
                        <td>${new Date(user.createTime).toLocaleString()}</td>
                        <td>
                            <button class="btn btn-sm btn-outline-primary btn-action" onclick="editUser(${user.id})">
                                <i class="bi bi-pencil"></i>
                            </button>
                            <button class="btn btn-sm btn-outline-danger btn-action" onclick="deleteUser(${user.id})">
                                <i class="bi bi-trash"></i>
                            </button>
                        </td>
                    `;
                    usersTableBody.appendChild(row);
                });
            } else {
                usersTableBody.innerHTML = '<tr><td colspan="7" class="text-center">暂无数据</td></tr>';
            }
        } else {
            showToast(data.message || '加载用户列表失败', 'danger');
        }
    } catch (error) {
        console.error('加载用户列表错误:', error);
        showToast('加载用户列表失败', 'danger');
    }
}

// 加载云账号列表
async function loadAccounts() {
    try {
        const response = await fetch('/api/cloud-accounts/current', {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });
        
        const data = await response.json();
        
        if (data.success) {
            const accountsTableBody = document.getElementById('accounts-table-body');
            accountsTableBody.innerHTML = '';
            
            if (data.data && data.data.length > 0) {
                data.data.forEach(account => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${account.id}</td>
                        <td>${account.name}</td>
                        <td>${getProviderName(account.provider)}</td>
                        <td>${account.region || '-'}</td>
                        <td><span class="badge bg-${account.status === 1 ? 'success' : 'secondary'}">${account.status === 1 ? '启用' : '禁用'}</span></td>
                        <td>${new Date(account.createTime).toLocaleString()}</td>
                        <td>
                            <button class="btn btn-sm btn-outline-primary btn-action" onclick="editAccount(${account.id})">
                                <i class="bi bi-pencil"></i>
                            </button>
                            <button class="btn btn-sm btn-outline-danger btn-action" onclick="deleteAccount(${account.id})">
                                <i class="bi bi-trash"></i>
                            </button>
                        </td>
                    `;
                    accountsTableBody.appendChild(row);
                });
            } else {
                accountsTableBody.innerHTML = '<tr><td colspan="7" class="text-center">暂无数据</td></tr>';
            }
        } else {
            showToast(data.message || '加载云账号列表失败', 'danger');
        }
    } catch (error) {
        console.error('加载云账号列表错误:', error);
        showToast('加载云账号列表失败', 'danger');
    }
}

// 显示用户模态框
function showUserModal(userId = null) {
    const modal = new bootstrap.Modal(document.getElementById('userModal'));
    const form = document.getElementById('user-form');
    const title = document.getElementById('userModalTitle');
    
    // 重置表单
    form.reset();
    document.getElementById('user-id').value = '';
    
    if (userId) {
        // 编辑模式
        title.textContent = '编辑用户';
        // 加载用户数据
        loadUser(userId);
    } else {
        // 添加模式
        title.textContent = '添加用户';
    }
    
    modal.show();
}

// 加载用户数据
async function loadUser(userId) {
    try {
        const response = await fetch(`/api/users/${userId}`, {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });
        
        const data = await response.json();
        
        if (data.success) {
            const user = data.data;
            document.getElementById('user-id').value = user.id;
            document.getElementById('user-email').value = user.email;
            document.getElementById('user-nickname').value = user.nickname || '';
            document.getElementById('user-role').value = user.role;
            document.getElementById('user-status').value = user.status;
        } else {
            showToast(data.message || '加载用户信息失败', 'danger');
        }
    } catch (error) {
        console.error('加载用户信息错误:', error);
        showToast('加载用户信息失败', 'danger');
    }
}

// 保存用户
async function saveUser() {
    const userId = document.getElementById('user-id').value;
    const userData = {
        email: document.getElementById('user-email').value,
        password: document.getElementById('user-password').value,
        nickname: document.getElementById('user-nickname').value,
        role: document.getElementById('user-role').value,
        status: parseInt(document.getElementById('user-status').value)
    };
    
    // 如果是编辑模式且密码为空，则不发送密码字段
    if (userId && !userData.password) {
        delete userData.password;
    }
    
    try {
        const url = userId ? `/api/users/${userId}` : '/api/users';
        const method = userId ? 'PUT' : 'POST';
        
        const response = await fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${authToken}`
            },
            body: JSON.stringify(userData)
        });
        
        const data = await response.json();
        
        if (data.success) {
            bootstrap.Modal.getInstance(document.getElementById('userModal')).hide();
            showToast(userId ? '用户更新成功' : '用户添加成功', 'success');
            loadUsers();
        } else {
            showToast(data.message || '保存用户失败', 'danger');
        }
    } catch (error) {
        console.error('保存用户错误:', error);
        showToast('保存用户失败', 'danger');
    }
}

// 编辑用户
function editUser(userId) {
    showUserModal(userId);
}

// 删除用户
async function deleteUser(userId) {
    if (!confirm('确定要删除此用户吗？')) {
        return;
    }
    
    try {
        const response = await fetch(`/api/users/${userId}`, {
            method: 'DELETE',
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });
        
        const data = await response.json();
        
        if (data.success) {
            showToast('用户删除成功', 'success');
            loadUsers();
        } else {
            showToast(data.message || '删除用户失败', 'danger');
        }
    } catch (error) {
        console.error('删除用户错误:', error);
        showToast('删除用户失败', 'danger');
    }
}

// 显示云账号模态框
function showAccountModal(accountId = null) {
    const modal = new bootstrap.Modal(document.getElementById('accountModal'));
    const form = document.getElementById('account-form');
    const title = document.getElementById('accountModalTitle');
    
    // 重置表单
    form.reset();
    document.getElementById('account-id').value = '';
    
    if (accountId) {
        // 编辑模式
        title.textContent = '编辑云账号';
        // 加载云账号数据
        loadAccount(accountId);
    } else {
        // 添加模式
        title.textContent = '添加云账号';
    }
    
    modal.show();
}

// 加载云账号数据
async function loadAccount(accountId) {
    try {
        const response = await fetch(`/api/cloud-accounts/${accountId}`, {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });
        
        const data = await response.json();
        
        if (data.success) {
            const account = data.data;
            document.getElementById('account-id').value = account.id;
            document.getElementById('account-name').value = account.name;
            document.getElementById('account-provider').value = account.provider;
            document.getElementById('account-region').value = account.region || '';
            document.getElementById('account-access-key').value = account.accessKey;
            document.getElementById('account-secret-key').value = '******'; // 不显示实际密钥
            document.getElementById('account-bucket').value = account.bucket || '';
            document.getElementById('account-endpoint').value = account.endpoint || '';
        } else {
            showToast(data.message || '加载云账号信息失败', 'danger');
        }
    } catch (error) {
        console.error('加载云账号信息错误:', error);
        showToast('加载云账号信息失败', 'danger');
    }
}

// 保存云账号
async function saveAccount() {
    const accountId = document.getElementById('account-id').value;
    const accountData = {
        name: document.getElementById('account-name').value,
        provider: document.getElementById('account-provider').value,
        region: document.getElementById('account-region').value,
        accessKey: document.getElementById('account-access-key').value,
        secretKey: document.getElementById('account-secret-key').value,
        bucket: document.getElementById('account-bucket').value,
        endpoint: document.getElementById('account-endpoint').value
    };
    
    // 如果是编辑模式且密钥是占位符，则不发送密钥字段
    if (accountId && accountData.secretKey === '******') {
        delete accountData.secretKey;
    }
    
    try {
        const url = accountId ? `/api/cloud-accounts/${accountId}` : '/api/cloud-accounts';
        const method = accountId ? 'PUT' : 'POST';
        
        const response = await fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${authToken}`
            },
            body: JSON.stringify(accountData)
        });
        
        const data = await response.json();
        
        if (data.success) {
            bootstrap.Modal.getInstance(document.getElementById('accountModal')).hide();
            showToast(accountId ? '云账号更新成功' : '云账号添加成功', 'success');
            loadAccounts();
        } else {
            showToast(data.message || '保存云账号失败', 'danger');
        }
    } catch (error) {
        console.error('保存云账号错误:', error);
        showToast('保存云账号失败', 'danger');
    }
}

// 编辑云账号
function editAccount(accountId) {
    showAccountModal(accountId);
}

// 删除云账号
async function deleteAccount(accountId) {
    if (!confirm('确定要删除此云账号吗？')) {
        return;
    }
    
    try {
        const response = await fetch(`/api/cloud-accounts/${accountId}`, {
            method: 'DELETE',
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });
        
        const data = await response.json();
        
        if (data.success) {
            showToast('云账号删除成功', 'success');
            loadAccounts();
        } else {
            showToast(data.message || '删除云账号失败', 'danger');
        }
    } catch (error) {
        console.error('删除云账号错误:', error);
        showToast('删除云账号失败', 'danger');
    }
}

// 获取提供商名称
function getProviderName(provider) {
    const providers = {
        'ALIYUN': '阿里云',
        'TENCENT': '腾讯云',
        'AWS': '亚马逊AWS',
        'AZURE': '微软Azure',
        'GOOGLE': '谷歌云'
    };
    return providers[provider] || provider;
}

// 显示提示消息
function showToast(message, type = 'info') {
    const toast = document.getElementById('toast');
    const toastMessage = document.getElementById('toast-message');
    
    // 设置消息
    toastMessage.textContent = message;
    
    // 设置样式
    toast.className = `toast bg-${type} text-white`;
    
    // 显示提示
    const bsToast = new bootstrap.Toast(toast);
    bsToast.show();
}